/**
 * @Title: MapHandler.java
 * @author zengshuai shi
 * @date 2015年8月4日 上午10:04:43
 */
package com.shanghaionstar.utils;

import android.graphics.Color;
import android.location.Address;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CircleOptions;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.ServiceSettings;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.mag.GeofenceInfoEntity;
import com.onstar.cn.mag.poi.Coordinate;
import com.onstar.cn.map.MapContainerImpl;
import com.onstar.cn.map.common.DriveMode;
import com.onstar.cn.map.common.DriveSegmentInfo;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.MapException;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.PoiType;
import com.onstar.cn.map.common.QueryType;
import com.onstar.cn.map.core.Circle;
import com.onstar.cn.map.core.OGeoPoint;
import com.onstar.cn.map.core.impl.OGeoPointImpl;
import com.onstar.cn.map.listener.ORouteHandlerListener;
import com.onstar.cn.map.listener.OSearchHandlerListener;
import com.onstar.cn.map.util.QueryOptions;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.model.FootPrintModel;
import com.shanghaionstar.nav.service.AbstractMapActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zengshuai shi
 * @ClassName: MapHandler
 * @Description: TODO
 * @date 2015年8月4日 上午10:04:43
 */
public class MapHandler {
    private static final LogManager logger = LogManager.getInstance();
    //	private OnCustomCoderGpsListener customCoderGpsListener;
    private AbstractMapActivity mapActivity;
    private float mapLevel = 15;

    private AMap mapView;

    private MapContainerImpl mapContainer;

    private Address address;// 记录我的位置的详细地址

    private PoiItemInfo myLocationPoiItemInfo = null;
    private PoiItemInfo searchedPoiItemInfo = null;
    private PoiItemInfo vehicleLocationPoiItemInfo = null;
    private PoiItemInfo startPoiItemInfo = null;

    public List<DriveSegmentInfo> getSegmentInfoList() {
        return segmentInfoList;
    }

    public void setSegmentInfoList(List<DriveSegmentInfo> segmentInfoList) {
        this.segmentInfoList = segmentInfoList;
    }

    List<DriveSegmentInfo> segmentInfoList;


    public PoiItemInfo getEndPoiItemInfo() {
        return endPoiItemInfo;
    }

    public void setEndPoiItemInfo(PoiItemInfo endPoiItemInfo) {
        this.endPoiItemInfo = endPoiItemInfo;
    }

    public PoiItemInfo getStartPoiItemInfo() {
        return startPoiItemInfo;
    }

    public void setStartPoiItemInfo(PoiItemInfo startPoiItemInfo) {
        this.startPoiItemInfo = startPoiItemInfo;
    }

    private PoiItemInfo endPoiItemInfo = null;
    private OGeoPointImpl myLocationPointer = null;


    LinearLayout poiVehicleIconLayout = null;
    LinearLayout poiManIconLayout = null;
    LinearLayout tempRouteStartIconLayout = null;
    LinearLayout tempRouteEndIconLayout = null;

    private final int POINT_TO_CITY_ERROR = 0x30001;// 对应PoiActivity中的message.what：POINT_TO_CITY_ERROR
    private final int SEARCH_SUCCESS = Constants.SEARCH_SUCCESS;// 0x50001
    private final int SEARCH_SUCCESS_REFRESH_ADAPTER = Constants.SEARCH_SUCCESS_REFRESH_ADAPTER;// 0x50006

    private final String CALCULATE_ROUTE = "CALCULATE_ROUTE";
    private final String CALCULATE_ROUTE_TEMP = "CALCULATE_ROUTE_TEMP";

    private List<PoiItemInfo> searchResultList = new ArrayList<PoiItemInfo>();

    public interface OnCustomCoderGpsListener {
        void onSuccessCoder(PoiItemInfo poiItemInfo, LocationType locationType);

        void onErrorCoder(LocationType locationType, MapException mapExp);
    }

    private OnCustomCoderGpsListener customCoderGpsListener;

    public void setCustomCoderGpsListener(OnCustomCoderGpsListener customCoderGpsListener) {
        this.customCoderGpsListener = customCoderGpsListener;
    }

    /**
     * 地图当前选中的poiitem
     */
    private PoiItemInfo mapPoi_PoiItemInfo;

    public PoiItemInfo getMapPoi_PoiItemInfo() {
        return mapPoi_PoiItemInfo;
    }

    public void setMapPoi_PoiItemInfo(PoiItemInfo mapPoi_PoiItemInfo) {
        this.mapPoi_PoiItemInfo = mapPoi_PoiItemInfo;
    }

    HashMap<String, LocationType> geoCoderGpsLocationTypeMap = new HashMap<String, LocationType>();// 根据LocationType区分：成功时，区分由车辆位置或我的位置经纬度获获详细地址
    // ，
    // 2.失败时，区分搜索poi错误和获取详细地址时的错误

    HashMap<String, String> calculateRouteTypeMap = new HashMap<String, String>();


    public Address getAddress() {
        return address;
    }

    public void setAddress(Address mAddress) {
        this.address = mAddress;
    }

    public PoiItemInfo getMyLocationPoiItemInfo() {
        return myLocationPoiItemInfo;
    }


    public PoiItemInfo getSearchedPoiItemInfo() {
        return searchedPoiItemInfo;
    }

    public void setSearchedPoiItemInfo(PoiItemInfo searchedPoiItemInfo) {
        this.searchedPoiItemInfo = searchedPoiItemInfo;
    }

    public PoiItemInfo getVehicleLocationPoiItemInfo() {
        return vehicleLocationPoiItemInfo;
    }

    public void setVehicleLocationPoiItemInfo(PoiItemInfo vehicleLocationPoiItemInfo) {
        this.vehicleLocationPoiItemInfo = vehicleLocationPoiItemInfo;
    }

    private String routeDistance = "";
    private String routeTime = "";

    public String getRouteDistance() {
        return routeDistance;
    }

    public void setRouteDistance(String routeDistance) {
        this.routeDistance = routeDistance;
    }

    public String getRouteTime() {
        return routeTime;
    }

    public void setRouteTime(String routeTime) {
        this.routeTime = routeTime;
    }


    public OGeoPointImpl getMyLocationPointer() {
        return myLocationPointer;
    }

    public List<PoiItemInfo> getSearchResultList() {
        return searchResultList;
    }

    private OnMapCallBack onMapCallBack;
    private OnMapSearchCallBack onMapSearchCallBack;
    private OnMapFootPrintCallBack onMapFootPrintCallBack;

    public void registOnMapCallBack(OnMapCallBack onMapCallBack) {
        this.onMapCallBack = onMapCallBack;
    }

    public void registOnMapSearchCallBack(OnMapSearchCallBack onMapSearchCallBack) {
        this.onMapSearchCallBack = onMapSearchCallBack;
    }

    public void registOnMapFootPrintCallBack(OnMapFootPrintCallBack onMapFootPrintCallBack) {
        this.onMapFootPrintCallBack = onMapFootPrintCallBack;
    }

    public void removeOnMapCallBack() {
        this.onMapCallBack = null;
    }

    public void removeOnMapSearchCallBack() {
        this.onMapSearchCallBack = null;
    }

    public void removeOnMapFootPrintCallBack() {
        this.onMapFootPrintCallBack = null;
    }


    public interface OnMapCallBack {
        void onFindLocateSuccess(LocationType locationType);

        void onFindLocateFail();
    }

    public interface OnMapFootPrintCallBack {
        void onFindLocateSuccess(PoiItemInfo poiItemInfo);

        void onFindLocateFail();
    }

    public interface OnMapSearchCallBack {

        void onSearchSuccess(List<PoiItemInfo> results, int pageIndex, int totalPages);

        void onSearchFail(LocationType locationType);

    }

    private OnRouteCalListener onRouteCalListener;

    public void registOnRouteCalListener(OnRouteCalListener onRouteCalListener) {
        this.onRouteCalListener = onRouteCalListener;
    }

    public interface OnRouteCalListener {
        void onRouteComplete();

        void onRouteError();
    }


    //	public MapHandler(MainTabActivity mainTabActivity, AMap mapView) {
//		this.mainTabActivity = mainTabActivity;
//		this.mapView = mapView;
//		OMapLongPressListener otl = new OMapLongPressListener() {
//			@Override
//			public void OnMapLongPress(OGeoPointImpl point) {
//
//			}
//		};
//		setTraffic(
//				Boolean.valueOf(BusinessUtil.getConfigValue(FinalConfigParams.ISTRAFFIC, mainTabActivity)));
//		UiSettings setting = this.mapView.getUiSettings();
//		setting.setZoomControlsEnabled(false);
//		mapContainer = new MapContainerImpl((OMapActivity) mainTabActivity, this.mapView, otl);
//		mapContainer.registerMapSearchListener(searchListener);
//		mapContainer.registerMapRouteListener(routeListener);
//		// 设置地图显示语言
//		if (DeviceUtil.isChineseLanguage()) {
//			mapView.setMapLanguage(AMap.CHINESE);
//			ServiceSettings.getInstance().setLanguage(ServiceSettings.CHINESE);
//		} else {
//			mapView.setMapLanguage(AMap.ENGLISH);
//			ServiceSettings.getInstance().setLanguage(ServiceSettings.ENGLISH);
//		}
//	}
    public MapHandler(AbstractMapActivity mapActivity, AMap mapView) {
        this.mapActivity = mapActivity;
        this.mapView = mapView;
//        UiSettings setting = this.mapView.getUiSettings();
//        setting.setZoomControlsEnabled(false);
        mapContainer = new MapContainerImpl(mapActivity, this.mapView, null);
        mapContainer.registerMapSearchListener(searchListener);
        mapContainer.registerMapRouteListener(routeListener);
        // 设置地图显示语言
        if (DeviceUtil.isChineseLanguage()) {
            mapView.setMapLanguage(AMap.CHINESE);
            ServiceSettings.getInstance().setLanguage(ServiceSettings.CHINESE);
        } else {
            mapView.setMapLanguage(AMap.ENGLISH);
            ServiceSettings.getInstance().setLanguage(ServiceSettings.ENGLISH);
        }
        setTraffic(PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConfigParams.ISTRAFFIC,true));
    }


    public void setTraffic(boolean isOpen) {
//        mapView.setTrafficEnabled(isOpen);
        logger.d("map isTrafficEnabled:" + mapView.isTrafficEnabled());
        mapContainer.setTraffic(isOpen);
//        mapView.invalidate();
//        MyPost.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mapView.invalidate();
//                if(mapContainer!=null)
//                    mapContainer.initMapView(mapLevel-=0.1);
//            }
//        },1*1000);
    }

    /**
     * @Title: getTraffic @Description: 是否已经打开交通流量 @param @return 设定文件 @return
     * boolean 返回类型 @throws
     */
    public boolean getTraffic() {
        return mapView.isTrafficEnabled();
    }

    public void setLocationPointer(LocationType locationType, double latitude, double longitude) {
        logger.d("Method setLocationPointer() locationType=" + locationType.name() + " latit=" + latitude + " longit="
                + longitude);
        try {
            switch (locationType) {
                case MYSELF:
                    myLocationPointer = new OGeoPointImpl(latitude, longitude);
                    break;
                case VEHICLE:
                    break;
                case POI:
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            logger.e(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    private boolean ifhasNext = false;

    public boolean IfhasNextPage() {
        return ifhasNext;
    }

    private void setIfhasNext(boolean ifhasNext) {
        this.ifhasNext = ifhasNext;
    }

    public OSearchHandlerListener searchListener = new OSearchHandlerListener() {
        @Override
        public void OnSearchResults(long id, QueryType type, List<PoiItemInfo> results, int pageIndex, int totalPages) {
            if (results.size() > Constants.POI_NUMBER || pageIndex < totalPages - 1) {
                setIfhasNext(true);
            } else {
                setIfhasNext(false);
            }
            if (onMapSearchCallBack != null) {
                onMapSearchCallBack.onSearchSuccess(results, pageIndex, totalPages);
            }
//			logger.d("OnSearchResults-------------------results=" + results.size() + "  pageIndex=" + pageIndex
//					+ "  totalPages=" + totalPages);
//			if (searchResultList != null)
//				searchResultList.clear();
//			if (results != null && results.size() > 0)
//				searchResultList.addAll(results);
//			if (pageIndex > 0) {
//				PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(SEARCH_SUCCESS_REFRESH_ADAPTER);// 查询成功，更新适配器
//			} else {
//				if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.Completed.getValue()) {
//					PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(SEARCH_SUCCESS);// 搜索成功
//				} else if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.StartPoitInProcess.getValue()) {
//					PoiLocationInfoInstance.getInstance().updateRouteSearchStatus();
//					PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.ROUTE_START_SEARCH_SUCCESS);
//				} else if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.EndPoitInProcess.getValue()) {
//					PoiLocationInfoInstance.getInstance().updateRouteSearchStatus();
//					PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.ROUTE_END_SEARCH_SUCCESS);
//				}
//			}
        }

        @Override
        public void OnSearchErrors(long id, MapException mapExp) {
//			logger.e("Method OnSearchErrors():id=" + id);
//			logger.e(mapExp.getErrorString(), mapExp.getExp());
//			LocationType lt = geoCoderGpsLocationTypeMap.remove(String.valueOf(id));
//			if (null != lt) {
//				switch (lt) {
//					case MYSELF:
//						if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.Completed.getValue())
//							PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(POINT_TO_CITY_ERROR);
//						else
//							PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.MY_LOCATION_NULL);
//						break;
//					case VEHICLE:
//						if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.Completed.getValue())
//							PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(POINT_TO_CITY_ERROR);
//						else
//							PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.GET_VEHICLE_LOCATION_FAILURE_ROUTE);
//						break;
//					case POI:
//						logger.e("Method OnSearchErrors():id=" + id + " LongPress to get poi failed");
//						break;
//					case Custom:
//						if (customCoderGpsListener != null) {
//							customCoderGpsListener.onErrorCoder(lt, mapExp);
//						}
//						break;
//					default:
//						break;
//				}
//			} else {
//				// TODO 还需添加route 生成时搜索失败的情况处理
//				if (PoiLocationInfoInstance.getInstance().getRouteSearchStatus() == RouteSearchStatusType.InProcess.getValue()) {
//					PoiLocationInfoInstance.getInstance().updateRouteSearchStatus();
//					logger.d("OnSearchErrors():id=" + id + " generate route failed: getRouteSearchStatus="
//							+ PoiLocationInfoInstance.getInstance().getRouteSearchStatus());
//				}
//				PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.SEARCH_FAIL);
//			}
        }

        @Override
        public void OnReverseResults(long id, PoiItemInfo poi) {
            LocationType lt = geoCoderGpsLocationTypeMap.remove(String.valueOf(id));
            if (null != lt) {
                logger.d("OnReverseResults():id=" + id + "  poiTitle=" + poi.getTitle() + "  LocationType=" + lt.name());
                switch (lt) {
                    case MYSELF:
                        mapActivity.getNavDataHolder().setMyPoi(poi);
                        initMyLocationPoiItemInfo(poi);
                        String mSelectCity = poi.getCityName();
                        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                            LoadCityList loadFile = new LoadCityList(mapActivity);
                            mSelectCity = loadFile.findByZhCity(mSelectCity);
                        }
                        logger.d("OnReverseResults(): mSelectCity=" + mSelectCity);
                        if (!CommonUtil.isNull(mSelectCity)) {
                            NavHolder.getInstance(mapActivity).setCurrentCity(mSelectCity);
                            NavHolder.getInstance(mapActivity).setCurrentProvince(poi.getProvince());
                            NavHolder.getInstance(mapActivity).setGeoPointImpl(new OGeoPointImpl(poi.getLatitude(), poi.getLongitude()));
                        }
                        if (onMapCallBack != null) {
                            onMapCallBack.onFindLocateSuccess(LocationType.MYSELF);
                        }
                        break;
                    case VEHICLE:
                        mapActivity.getNavDataHolder().setVehiclePoi(poi);
                        initVehicleLocationPoiItemInfo(poi);
                        if (onMapCallBack != null) {
                            onMapCallBack.onFindLocateSuccess(LocationType.VEHICLE);
                        }
                        break;
                    case POI:
                        break;
                    case Custom:
                        if (customCoderGpsListener != null) {
                            customCoderGpsListener.onSuccessCoder(poi, lt);
                        }
                        break;
                    case FOOTPRINT:
                        if (onMapFootPrintCallBack != null) {
                            onMapFootPrintCallBack.onFindLocateSuccess(poi);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

    };

    private ORouteHandlerListener routeListener = new ORouteHandlerListener() {

        @Override
        public void OnCalculateTempRoute(long id, PoiItemInfo routeStartPoiItemInfo, PoiItemInfo routeEndPoiItemInfo) {
            logger.d("OnCalculateTempRoute():id=" + id + "  routeStartPoiItemInfo=" + routeStartPoiItemInfo.getTitle()
                    + "  routeEndPoiItemInfo=" + routeEndPoiItemInfo.getTitle());
            caculateTempRoute(routeStartPoiItemInfo, routeEndPoiItemInfo);
        }

        @Override
        public void OnRouteComplete(long id) {
            setRouteDistance(mapContainer.getRouteDistance());
            setRouteTime(mapContainer.getRouteTime());
            List<DriveSegmentInfo> driveSegmentInfoList = mapContainer.getDriveSegmentResultList();
//			String type = calculateRouteTypeMap.remove(String.valueOf(id));
//			PoiLocationInfoInstance.getInstance().setRouteDistance(mapContainer.getRouteDistance());
//			PoiLocationInfoInstance.getInstance().setRouteTime(mapContainer.getRouteTime());
//			logger.d("OnRouteComplete():type=" + type + " id=" + id + "   routeDistance=" + mapContainer.getRouteDistance()
//					+ "  routeTime=" + mapContainer.getRouteTime());
//			if (type.equalsIgnoreCase(CALCULATE_ROUTE_TEMP)) {
//				clearTempRoutePoints();
//				clearRouteOverlay();
//				mapContainer.showTempRoute(false);
//				Message msg = Message.obtain();
//				msg.what = Constants.UPDATE_ROUTE_PROGRESSBAR;
//				Bundle bundle = new Bundle();
//				bundle.putBoolean(Constants.ROUTE_PROGREEBAR_SHOWING, false);
//				msg.setData(bundle);
//				PoiLocationInfoInstance.getInstance().getCommonHandler().sendMessage(msg);
//				PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.POI_ACTIVITY_SHOW_TEMP_ROUTE_TIPS);
//
//				BusinessUtil.sendReportByClickType(mainTabActivity,
//						com.shanghaionstar.enumtype.FunctionNameFindId.ClickMapToViewRoute.getStringValue());
//
//			} else {
//				PoiLocationInfoInstance.getInstance().setRouteSearchStatus(RouteSearchStatusType.Completed);
//				List<DriveSegmentInfo> driveSegmentInfoList = mapContainer.getDriveSegmentResultList();
//				PoiLocationInfoInstance.getInstance().setDriveSegmentInfoList(driveSegmentInfoList);
//				PoiLocationInfoInstance.getInstance().getCommonHandler().sendEmptyMessage(Constants.ROUTE_SEARCH_SUCCESS);
            setSegmentInfoList(mapContainer.getDriveSegmentResultList());
            onRouteCalListener.onRouteComplete();
//			}
        }

        @Override
        public void OnRouteErrors(long id, MapException mapException) {
//			logger.e("OnRouteErrors():id=" + id + "   errorMessage=" + mapException.getErrorString());
//			logger.e(mapException.getErrorString(), mapException.getExp());
//			PoiLocationInfoInstance.getInstance().setRouteSearchStatus(RouteSearchStatusType.Completed);
//			logger.d("OnRouteErrors():id=" + id + " generate route failed: getRouteSearchStatus="
//					+ PoiLocationInfoInstance.getInstance().getRouteSearchStatus());
//			Message msg = Message.obtain();
//			msg.what = Constants.SEARCH_FAIL;
//			msg.obj = mapException.getErrorString();
//			msg.sendToTarget();
        }

        @Override
        public void OnRouteStartPoint(LocationType type) {
            logger.e("OnRouteStartPoint():LocationType=" + type.name());
            clearRouteOverlay();
        }

        @Override
        public void OnRouteEndPoint(LocationType type) {
            logger.e("OnRouteStartPoint():LocationType=" + type.name());
        }

    };

    public void initMapView(int map_level) {
        this.mapLevel = map_level;
        mapContainer.initMapView(map_level);
    }

    public void searchByName(String key, String poiType, String cityCode) {
        logger.d("Method searchByName() key=" + key + "*******poiType=" + poiType + "*******citycode=" + cityCode);
        if (null == searchResultList)
            searchResultList = new ArrayList<PoiItemInfo>();
        else
            searchResultList.clear();
        QueryOptions options = new QueryOptions();
        options.setiPageNumber(0);
        options.setiPageCount(10);
        mapContainer.searchByName(key, PoiType.fromValue(poiType), cityCode, options);
    }

    /**
     * @Title: nextPageResult @Description: 显示下一页结果 @param @throws Exception
     * 设定文件 @return void 返回类型 @throws
     */
    public void nextPageResult() throws Exception {
        logger.d("Method nextPageResult()");
        mapContainer.nextPageResult();
    }

    public void searchNearBy(String key, String poiType, int radius, String cityCode, OGeoPointImpl ogeo) {
        logger.d("Method searchNearBy() key=" + key + "*******poiType=*****" + poiType + "*******radius=**" + radius);
        if (null == searchResultList)
            searchResultList = new ArrayList<PoiItemInfo>();
        else
            searchResultList.clear();
        QueryOptions options = new QueryOptions();
        options.setiPageNumber(0);
        options.setiPageCount(10);
        Circle circle = null;
        if (ogeo == null)
            circle = new Circle(radius, getMyLocationPointer());
        else
            circle = new Circle(radius, ogeo);
        options.setCircle(circle);
        mapContainer.searchNearBy(key, PoiType.fromValue(poiType), cityCode, options);
    }

    public void showRoute() {
        mapContainer.showRoute();
    }

    public void setMapView(AMap mapView) {
        mapContainer.setmMapView(mapView);
    }

    public void initMapView(int map_level, PoiItemInfo poiItemInfo) {
        logger.d("Method initMapView(int map_level, String cityName,oiItemInfo poiItemInfo)");
        OGeoPoint center = new OGeoPointImpl(poiItemInfo.getLatitude(), poiItemInfo.getLongitude());
        mapContainer.initMapView(map_level, center);
    }

    public void initVariable() {

        myLocationPoiItemInfo = null;
        searchedPoiItemInfo = null;
        vehicleLocationPoiItemInfo = null;

        myLocationPointer = null;

        if (null != searchResultList)
            searchResultList.clear();

    }


    public void clearMapOverlays() {
        mapContainer.clearMapOverlays();
    }

    /**
     * @Title: clearRouteOverlay @Description: 去除路径信息，并清除提示框 @param 设定文件 @return
     * void 返回类型 @throws
     */
    public void clearRouteOverlay() {
        mapContainer.clearRouteOverlay();
    }

    public void clearOverlay() {
        clearMapOverlays();
        clearRouteOverlay();
    }


    //	public void initMyLocationPoiItemInfo(PoiItemInfo poiItemInfo) {
//		if (null == myLocationPoiItemInfo)
//			myLocationPoiItemInfo = new PoiItemInfo();
//		String city = poiItemInfo.getCityName();
//		if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
//			LoadCityList cityList = new LoadCityList(mainTabActivity);
//			city = cityList.findByZhCity(poiItemInfo.getCityName());
//		}
//		myLocationPoiItemInfo.setCityName(city);
//		myLocationPoiItemInfo.setLatitude(poiItemInfo.getLatitude());
//		myLocationPoiItemInfo.setLongitude(poiItemInfo.getLongitude());
//		String title = poiItemInfo.getTitle();
//		if (!CommonUtil.isNull(title)) {
//			myLocationPoiItemInfo.setSnippet(poiItemInfo.getTitle());// 存储详细地址
//		} else {
//			// 无地址就显示为当前位置
//			myLocationPoiItemInfo.setSnippet(mainTabActivity.getString(R.string.poi_not_map_mylocation_str));
//		}
//		myLocationPoiItemInfo.setTitle(mainTabActivity.getString(R.string.poi_route_poi_str));
//		myLocationPoiItemInfo.setTelphone("");
//		myLocationPoiItemInfo.setCurrentLocationTag(true);
//	}
//
    public void initVehicleLocationPoiItemInfo(PoiItemInfo poiItemInfo) {
        if (null == vehicleLocationPoiItemInfo)
            vehicleLocationPoiItemInfo = new PoiItemInfo();
        vehicleLocationPoiItemInfo.setCityName(poiItemInfo.getCityName());
        vehicleLocationPoiItemInfo.setLatitude(poiItemInfo.getLatitude());
        vehicleLocationPoiItemInfo.setLongitude(poiItemInfo.getLongitude());
        String title = poiItemInfo.getTitle();
        if (!CommonUtil.isNull(title)) {
            vehicleLocationPoiItemInfo.setAddress(poiItemInfo.getTitle());// 存储详细地址
        } else {
            // 无地址就显示为车辆位置为详细地址
            vehicleLocationPoiItemInfo.setAddress(mapActivity.getString(R.string.poi_route_vehicle_str));
        }
        vehicleLocationPoiItemInfo.setTitle(mapActivity.getString(R.string.poi_route_vehicle_str));
        vehicleLocationPoiItemInfo.setTelphone("");
        vehicleLocationPoiItemInfo.setCurrentLocationTag(true);// TODO
    }
//
//	public void initSearchedPoiItemInfo(PoiItemInfo poiItemInfo) {
//		logger.d("Method initSearchedPoiItemInfo():poiItemInfo=" + poiItemInfo.toString());
//		if (null == searchedPoiItemInfo)
//			searchedPoiItemInfo = new PoiItemInfo();
//		searchedPoiItemInfo.setCityName(poiItemInfo.getCityName());
//		searchedPoiItemInfo.setLatitude(poiItemInfo.getLatitude());
//		searchedPoiItemInfo.setLongitude(poiItemInfo.getLongitude());
//		String title = poiItemInfo.getTitle();
//		if (!CommonUtil.isNull(title)) {
//			searchedPoiItemInfo.setSnippet(poiItemInfo.getSnippet());// 存储详细地址
//		} else {
//			// 无地址就显示为空
//			searchedPoiItemInfo.setSnippet("");// 存储详细地址
//		}
//		searchedPoiItemInfo.setTitle(poiItemInfo.getTitle());
//		if (null != poiItemInfo.getTelphone())
//			searchedPoiItemInfo.setTelphone(poiItemInfo.getTelphone());
//		else
//			searchedPoiItemInfo.setTelphone("");
//		searchedPoiItemInfo.setCurrentLocationTag(true);// TODO 此处应该设置成true or
//		// false？
//	}

    public void geoCoderGps(double latitude, double longitude, final LocationType locationType) {
        long id = mapContainer.geoCoderGps(latitude, longitude);
        geoCoderGpsLocationTypeMap.put(String.valueOf(id), locationType);
        logger.d("geoCoderGps():latitude=" + latitude + "  longitude=" + longitude + "  locationType="
                + locationType.name() + "\n result:" + id);
    }

    private View vehiclePopView;

    public void showLocation(final LocationType locationType, final PoiItemInfo poiItemInfo) {
        if (poiItemInfo == null) {
            return;
        }
        logger.d("Method showLocation() locationType=" + locationType.name() + " poiTile=" + poiItemInfo.getTitle()
                + " latit=" + poiItemInfo.getLatitude() + " longit=" + poiItemInfo.getLongitude());

        // Constants.lastLocationType = locationType.getValue();

        clearRouteOverlay();// 去除临时路径
        clearTempRoutePoints();// 清空临时起始点
        if (LocationType.VEHICLE == locationType) {
            mapView.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    vehiclePopView = LayoutInflater.from(mapActivity).inflate(R.layout.nav_vehicle_pop_window, null);
                    TextView title = (TextView) vehiclePopView.findViewById(R.id.title);
                    String time = DateFormatUtil.formatVehicleLocateTime(NavHolder.getInstance(mapActivity).getVehicleLocationTime(), 8);
                    title.setText(mapActivity.getString(R.string.nav_vehicle_time, time));
                    return vehiclePopView;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });
            mapContainer.showLocation(locationType, poiItemInfo, true);
        } else {
            mapContainer.showLocation(locationType, poiItemInfo, false);
        }
    }

    /**
     * @Title: clearLocations @Description: 清除地图中的三点 @param 设定文件 @return void
     * 返回类型 @throws
     */
    public void clearLocations() {
        mapContainer.clearLocations();
    }

    /**
     * @Title: clearTempRoutePoints @Description: 起初临时路径中的起始点信息 @param
     * 设定文件 @return void 返回类型 @throws
     */
    public void clearTempRoutePoints() {
        mapContainer.clearTempRoutePoints();
    }

    /**
     * @Title: caculateRoute @Description: 计算路径 @param @param
     * routeStartPoiItemInfo @param @param routeEndPoiItemInfo
     * 设定文件 @return void 返回类型 @throws
     */
    public void caculateRoute(PoiItemInfo routeStartPoiItemInfo, PoiItemInfo routeEndPoiItemInfo) {
        logger.d("caculateRoute(): routeStartPoiItemInfo title=" + routeStartPoiItemInfo.getTitle() + " latitude="
                + routeStartPoiItemInfo.getLatitude() + "   longitude=" + routeStartPoiItemInfo.getLongitude());
        logger.d("caculateRoute(): routeEndPoiItemInfo title=" + routeEndPoiItemInfo.getTitle() + " latitude="
                + routeEndPoiItemInfo.getLatitude() + "   longitude=" + routeEndPoiItemInfo.getLongitude());

        // mapContainer.setDriveMode(Constants.dirverMode);

        // 第三个、第四个参数必须为中文版的小时、分钟
        long i = mapContainer.caculateRoute(routeStartPoiItemInfo, routeEndPoiItemInfo, "小时", " 分钟");
        calculateRouteTypeMap.put(String.valueOf(i), CALCULATE_ROUTE);
    }

    /**
     * @Title: caculateRoute @Description: 计算路径 @param @param
     * routeStartPoiItemInfo @param @param routeEndPoiItemInfo
     * 设定文件 @return void 返回类型 @throws
     */
    public void caculateRouteByMode(PoiItemInfo routeStartPoiItemInfo, PoiItemInfo routeEndPoiItemInfo, int driveMode) {
        logger.d("caculateRoute(): routeStartPoiItemInfo title=" + routeStartPoiItemInfo.getTitle() + " latitude="
                + routeStartPoiItemInfo.getLatitude() + "   longitude=" + routeStartPoiItemInfo.getLongitude());
        logger.d("caculateRoute(): routeEndPoiItemInfo title=" + routeEndPoiItemInfo.getTitle() + " latitude="
                + routeEndPoiItemInfo.getLatitude() + "   longitude=" + routeEndPoiItemInfo.getLongitude());

         mapContainer.setDriveMode(driveMode);

        // 第三个、第四个参数必须为中文版的小时、分钟
        long i = mapContainer.caculateRouteByMode(routeStartPoiItemInfo, routeEndPoiItemInfo, "小时", " 分钟",driveMode);
        calculateRouteTypeMap.put(String.valueOf(i), CALCULATE_ROUTE);
    }

    /**
     * @Title: caculateTempRoute @Description: 计算临时路径 @param @param
     * routeStartPoiItemInfo @param @param routeEndPoiItemInfo
     * 设定文件 @return void 返回类型 @throws
     */
    public void caculateTempRoute(PoiItemInfo routeStartPoiItemInfo, PoiItemInfo routeEndPoiItemInfo) {
        logger.d("caculateTempRoute(): routeStartPoiItemInfo title=" + routeStartPoiItemInfo.getTitle() + " latitude="
                + routeStartPoiItemInfo.getLatitude() + "   longitude=" + routeStartPoiItemInfo.getLongitude());
        logger.d("caculateTempRoute(): routeEndPoiItemInfo title=" + routeEndPoiItemInfo.getTitle() + " latitude="
                + routeEndPoiItemInfo.getLatitude() + "   longitude=" + routeEndPoiItemInfo.getLongitude());

        // mMapContainer.setDriveMode(Constants.dirverMode);

        // 第三个、第四个参数必须为中文版的小时、分钟
        //TODO此功能暂时取消
//		long i = mapContainer.caculateTempRoute(routeStartPoiItemInfo, routeEndPoiItemInfo,
//				navFragments.getActivity().getString(R.string.poi_route_unit_hour_str),
//				navFragments.getActivity().getString(R.string.poi_route_unit_minutes_str));
//		calculateRouteTypeMap.put(String.valueOf(i), CALCULATE_ROUTE_TEMP);
    }


    public void removeView(View view) {
        mapContainer.removeMapView(view);
    }

    public void clearLayout(View linearLayout) {
        mapContainer.clearLayout(linearLayout);
    }

    public void clearLayouts() {
        clearLayout(poiVehicleIconLayout);
        clearLayout(poiManIconLayout);
        clearLayout(tempRouteStartIconLayout);
        clearLayout(tempRouteEndIconLayout);
    }


    public void setGeoFenceCircle(GeofenceInfoEntity mGeoFenceInfo) {
        LogManager.getInstance().d("range is " + mGeoFenceInfo.getRange() + mGeoFenceInfo.getRangeUnit());
        double dRange = convertRangeToDouble(mGeoFenceInfo.getRange(), mGeoFenceInfo.getRangeUnit());
        int iRange = (int) dRange;
        float zoomLevel = 3f;
        switch (iRange) {
            case 100:
                zoomLevel = 20f;
                break;
            case 500:
                zoomLevel = 15f;
                break;
            case 1000:
                zoomLevel = 15f;
                break;
            case 2000:
                zoomLevel = 14f;
                break;
            case 5000:
                zoomLevel = 13f;
                break;
            case 10000:
                zoomLevel = 12f;
                break;
            case 20000:
                zoomLevel = 8f;
                break;
            case 50000:
                zoomLevel = 6f;
                break;
            case 100000:
                zoomLevel = 5f;
                break;
            default:
                zoomLevel = 12f;
                break;
        }
        Coordinate coordinate = mGeoFenceInfo.getCenterPoiCoordinate();

        mapView.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                .position(getMyLatLng(coordinate.getLatitude() + "", coordinate.getLongitude() + ""))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.onstar_geofence_preview_icon)));

        mapView.moveCamera(CameraUpdateFactory
                .newLatLngZoom(getMyLatLng(coordinate.getLatitude() + "", coordinate.getLongitude() + ""), zoomLevel));// 设置指定的可视区域地图

        mapView.addCircle(new CircleOptions().strokeWidth(1).strokeColor(mapActivity.getResources().getColor(R.color.guide_item_font_color))
                .center(getMyLatLng(coordinate.getLatitude() + "", coordinate.getLongitude() + "")).radius(dRange)
                .fillColor(Color.argb(50, 0, 0, 255)));
    }


    private LatLng getMyLatLng(String latitude, String longitude) {
        LatLng latLng = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));
        return latLng;
    }

//	public void setCustomCoderGpsListener(OnCustomCoderGpsListener customCoderGpsListener) {
//		this.customCoderGpsListener = customCoderGpsListener;
//	}

    private double convertRangeToDouble(String range, String unit) {
        if (CommonUtil.isNull(range))
            return 0;
        int numberUnit = 1;

        if (unit != null && (unit.equalsIgnoreCase(Constants.RANGE_UNIT) || unit.equalsIgnoreCase("千米"))) {
            numberUnit = 1000;
        }

        if (range.contains(mapActivity.getString(R.string.geofence_range_unit_km)))
            range = range.replace(mapActivity.getString(R.string.geofence_range_unit_km), "");
        if (range.contains(mapActivity.getString(R.string.geofence_range_unit_m)))
            range = range.replace(mapActivity.getString(R.string.geofence_range_unit_m), "");
        return Double.valueOf(range) * numberUnit;
    }

    public void initMyLocationPoiItemInfo(PoiItemInfo poiItemInfo) {
        if (null == myLocationPoiItemInfo)
            myLocationPoiItemInfo = new PoiItemInfo();
        String city = poiItemInfo.getCityName();
        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
            LoadCityList cityList = new LoadCityList(mapActivity);
            city = cityList.findByZhCity(poiItemInfo.getCityName());
        }
        myLocationPoiItemInfo.setCityName(city);
        myLocationPoiItemInfo.setLatitude(poiItemInfo.getLatitude());
        myLocationPoiItemInfo.setLongitude(poiItemInfo.getLongitude());
        String title = poiItemInfo.getTitle();
        if (!CommonUtil.isNull(title)) {
            myLocationPoiItemInfo.setAddress(poiItemInfo.getTitle());// 存储详细地址
        } else {
            // 无地址就显示为当前位置
            myLocationPoiItemInfo.setAddress(mapActivity.getString(R.string.poi_not_map_mylocation_str));
        }
        myLocationPoiItemInfo.setTitle(mapActivity.getString(R.string.poi_route_poi_str));
        myLocationPoiItemInfo.setTelphone("");
        myLocationPoiItemInfo.setCurrentLocationTag(true);
    }


    public Marker addMarker(FootPrintModel footPrintModel) {
        Marker marker = mapView.addMarker(new MarkerOptions().anchor(1f, 1f)
                .position(footPrintModel.latLng).draggable(true)
                .title(footPrintModel.title).snippet(footPrintModel.seqId)
//                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
//                .icon(BitmapDescriptorFactory.fromResource(R.drawable.onstar_geofence_preview_icon)));
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.nav_foot_print_marker_big)));
        marker.setObject(footPrintModel);
//        marker.showInfoWindow();
        return marker;
    }

    public Marker addFlagMarker(FootPrintModel footPrintModel) {
        Marker marker = mapView.addMarker(new MarkerOptions().anchor(1f, 1f)
                .position(footPrintModel.latLng).draggable(true)
                .title(footPrintModel.title).snippet(footPrintModel.seqId)
//                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
//                .icon(BitmapDescriptorFactory.fromResource(R.drawable.onstar_geofence_preview_icon)));
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.nav_foot_print_flag)));
//        marker.showInfoWindow();
        marker.setObject(footPrintModel);
        return marker;
    }

    /**
     * 去除 poicount属性
     *
     * @param footPrintModel
     * @return
     */
    private FootPrintModel cloneFootModel(FootPrintModel footPrintModel) {
        FootPrintModel showFootPrintModel = new FootPrintModel();
        showFootPrintModel.cityCount = footPrintModel.cityCount;
        showFootPrintModel.rank = footPrintModel.rank;
        showFootPrintModel.seqId = footPrintModel.seqId;
        showFootPrintModel.latLng = footPrintModel.latLng;
        showFootPrintModel.cityName = footPrintModel.cityName;
        return showFootPrintModel;
    }
}
